/*
 * fifoQueueHelper.c
 *
 *  Created on: Feb 8, 2010
 *      Author: diqiu
 */

#include "include.h"
#include "DataType.h"

/* Enqueue a packet into a packet queue.
 * 	packet:	Packet to be enqueued
 * 	queue:	Pointer to the queue
 */
void enqueue(Packet packet, PacketQueue *packetQueue) {
	// Update head and tail accordingly
	if (packetQueue->tail == packetQueue->head -1) {
		// The queue is full.
		packetQueue->head = (packetQueue->head == 0) ? PACKETQUEUE_SIZE-1 : packetQueue->head-1;
		packetQueue->tail = (packetQueue->tail == 0) ? PACKETQUEUE_SIZE-1 : packetQueue->tail-1;
	} else {
		// The queue is not full.
		packetQueue->head = (packetQueue->head == 0) ? PACKETQUEUE_SIZE-1 : packetQueue->head-1;
	}
	// Enqueue the new packet
	Packet *updatePacket = packetQueue->queue+packetQueue->head;
	updatePacket->emulatedMouse = packet.emulatedMouse;
	updatePacket->xPos = packet.xPos;
	updatePacket->yPos = packet.yPos;
}

/* Dequeue a packet from a packet queue
 * 	packetQueue:	Pointer to the queue
 * Returns the packet dequeued
 */
Packet dequeue(PacketQueue *packetQueue) {
	// If queue is empty return NULL
	if (isQueueEmpty(packetQueue)) {
		return NULL;
	}
	// Setup the return packet
	Packet packet;
	packet.emulatedMouse = (packetQueue->queue+packetQueue->tail)->emulatedMouse;
	packet.xPos = (packetQueue->queue+packetQueue->tail)->xPos;
	packet.yPos = (packetQueue->queue+packetQueue->tail)->yPos;

	// Update tail
	packetQueue->tail = (packetQueue->tail == 0) ? PACKETQUEUE_SIZE-1 : packetQueue->tail-1;

	return packet;
}

/* Is the packet queue empty?
 * 	packetQueue:	Pointer to the queue
 * Returns 1 if queue is empty, 0 otherwise.
 */
int isQueueEmpty(PacketQueue *packetQueue) {
	return (packetQueue->head == packetQueue->tail) ? 1 : 0;
}
